<template>
  <!-- 回收下单 -->
  <el-dialog class="pick-dialog" title="确认回收订单" @close="close" :visible.sync="dialogVisible" :close-on-click-modal="false" append-to-body width="960px">
    <div class="" v-loading="loading">
      <el-divider content-position="left">商品信息</el-divider>
      <div class="card-box">

        <el-descriptions title="" :column="2" border :labelStyle="{width:'100px'}" :contentStyle="{minWidth:'200px'}">
          <el-descriptions-item label="回收状态">
            <el-tag :type="commonMaps.backStateMap[huishouObj.backState||1].type">{{commonMaps.backStateMap[huishouObj.backState||1].label}}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="拒收原因" v-if="huishouObj.backState==5">{{huishouObj.jushouRemark?huishouObj.jushouRemark:'暂无'}}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{huishouObj.contactPhone}}</el-descriptions-item>
          <el-descriptions-item label="游戏">{{huishouObj.gameName}}</el-descriptions-item>
          <el-descriptions-item label="游戏账号">
            <div>{{huishouObj.accountNumber}} <el-button type="primary" size="mini" @click="heihaoCheck">黑号查询</el-button></div>

          </el-descriptions-item>
          
          <el-descriptions-item label="实名" v-if="huishouObj.relname">{{huishouObj.relname}}</el-descriptions-item>
          <el-descriptions-item :span="2" label="区服">{{huishouObj.region}}</el-descriptions-item>
          <el-descriptions-item label="简介" :span="2">
            <div style="max-height: 200px;overflow-y: auto;white-space: pre-wrap;">{{huishouObj.des}}</div>
          </el-descriptions-item>
          <!-- <el-descriptions-item label="图片" :span="2">
          <div class="img-box flex">
            <div v-for="(item, ind) in list" :key="item" >
              <img :src="item" @click="review(ind)"/>
            </div>
          </div>
        </el-descriptions-item> -->
          <el-descriptions-item label="AI估价">
            <span style="color:red;">{{huishouObj.gujiaAmount?('¥'+ huishouObj.gujiaAmount):'暂无AI估价'}}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <el-divider content-position="left">订单信息</el-divider>
      <el-form :model="ruleForm" ref="ruleForm" label-width="120px" :inline="true" :rules="rules" class="new_form_box form-box">
        <div class="tip">
          温馨提示:包赔服务由包赔商提供,平台不承担包赔责任！
        </div>
        <el-form-item class="row" label-width="80px" label="包赔商:" prop="guaranteeTenantId" v-if="baopeiList.length>0">
          <div class="baopei-box">
            <div class="flex">
              <div class="baopei-item flex" :class="{active:ruleForm.guaranteeTenantId==item.tenantId}" v-for="item in baopeiList" :key="item.tenantId" @click="tenantChange(item)">
              <img :src="item.avatar" alt="" style="width:40px;height:40px">
                <div class="flex alc">
                  <div class="tit">{{item.tenantName}}</div>
                  <!-- <el-popover :width="400" trigger="hover" :content="item.introduction" placement="top-start">
                      <template slot="reference">
                          <div class="zdy-des des">{{ item.introduction }}</div>
                      </template>
                  </el-popover> -->
                  <div class="icon">
                    <img v-if="ruleForm.guaranteeTenantId!=item.tenantId" src="../../../../assets/img/weixuan.png" alt="">
                    <img v-if="ruleForm.guaranteeTenantId==item.tenantId" src="../../../../assets/img/yixuan.png" alt="">
                  </div>
                </div>
              </div>
            </div>
            <div style="color: #999;" v-if="baopeiDuanSetObj&&baopeiDuanSetObj.shuoming">
              说明：{{ baopeiDuanSetObj.shuoming }}
            </div>
          </div>
        </el-form-item><br />
        <el-form-item label="包赔客服:" prop="guaranteeId" v-if="ruleForm.guaranteeTenantId">
          <el-select  v-model="ruleForm.guaranteeId" clearable @change="kefuChange">
            <el-option :label="item.name" :value="item.customer" v-for="item in kefuList" :key="item.customer"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="包赔收款账户:" prop="zhanghu" v-if="ruleForm.guaranteeTenantId">
          <el-select v-model="ruleForm.zhanghu" clearable @change="zhanghuChange">
            <el-option :label="item.collectionAccountName+'('+item.collectionUserName+item.collectionAccount+')'" :value="item.id" v-for="item in baopeiBankList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="包赔费:"  prop="guaranteeAmount" v-if="ruleForm.guaranteeTenantId">
          <el-input disabled v-model="ruleForm.guaranteeAmount" type="text" placeholder="包赔费" ></el-input>
        </el-form-item>
        <el-form-item label="手续费:"  prop="guaranteeServiceAmount" v-if="ruleForm.guaranteeTenantId">
          <el-input disabled v-model="ruleForm.guaranteeServiceAmount" type="text" placeholder="手续费" ></el-input>
        </el-form-item>
         <el-form-item label="线索费:"  prop="xiansuofei" v-if="huishouObj.source == 4">
          <el-input disabled  v-model="xiansuofei" type="text" placeholder="手续费" ></el-input>
        </el-form-item>
        <el-form-item label="回收金额:" prop="backAmount">
          <el-input :disabled="huishouObj.source==4" v-model="ruleForm.backAmount" type="text" placeholder="请输入回收金额" @change="computedTotal"></el-input>
        </el-form-item>
        <el-form-item label="游戏账号:" prop="accountNumber">
          <el-input v-model="ruleForm.accountNumber" type="text" placeholder="请输入游戏账号"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="accountPassword">
          <el-input v-model="ruleForm.accountPassword" type="text" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="绑定手机号:" prop="securityPhone">
          <el-input v-model="ruleForm.securityPhone" type="text" placeholder="请输入绑定手机号"></el-input>
        </el-form-item>
        <br />
        <el-form-item label="卖家客服:" prop="sellerId" v-if="isJingpai">
          <el-select v-model="ruleForm.sellerId" clearable>
            <el-option :label="item.name" :value="item.customer" v-for="item in sellerKefuList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卖家收款账户:" prop="zhanghuSeller" v-if="isJingpai">
          <el-select v-model="ruleForm.zhanghuSeller" clearable @change="zhanghuChangeSeller">
            <el-option :label="item.collectionAccountName+'('+item.collectionUserName+item.collectionAccount+')'" :value="item.id" v-for="item in sellerBankList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="应付金额:" prop="actualAmount">
          <el-input   v-model="ruleForm.actualAmount" type="text" 
            placeholder="请输入应付金额"></el-input>
        </el-form-item><br/> -->
        <el-form-item label="备注:" prop="remark">
          <el-input type="textarea" style="width:600px" v-model="ruleForm.remark" placeholder="请输入备注" show-word-limit :rows="3" maxlength="300"></el-input>
        </el-form-item>
      </el-form>
      <div class="sfk">
        <span>应付金额：</span>
        <span class="price">
          <span>¥</span><span class="txt">{{ ruleForm.actualAmount||0 }}</span>
        </span>
      </div>
        <div style="justify-content: flex-end;" class="flex" v-if="huishouObj.source==4 &&checkPermi(['caigou:payNow'])">
        <div style="width: auto;">
          <payWayLsit :showYue="2" :payWay='payWay' ref="payWayLsit" @selectPayway="selectPayway"></payWayLsit>
        </div>

      </div>

      <div class="center">
        <el-button @click="close('ruleForm')">取消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">{{huishouObj.source==4?'立即支付':'确认订单'}}</el-button>
      </div>

       <chongzhiYue ref="chongzhiYue"></chongzhiYue>
    </div>
  </el-dialog>
</template>

<script>
import chongzhiYue from "@/views/tenantPages/moneys/components/chongzhiYue.vue";
import payWayLsit from "../../components/payWayLsit.vue";
import onSelfApi from "@/api/retrieveManage/onSelf.js";
import phoneApi from "@/api/phoneManage";
import { listBlack } from "@/api/black/black.js";
import kefuApi from "@/api/kefu/index";
import customerServiceApi from "@/api/pickUp/customerService";
export default {
  name: "pick",
  components: {payWayLsit , chongzhiYue},
  data() {
    var priceRule = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        if (!this.priceReg.test(value)) {
          callback(new Error("请输入正确的价格"));
        }
        callback();
      }
    };
    var phoneRule = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        if (!this.phoneReg.test(value)) {
          callback(new Error("手机号格式不正确"));
        }
        callback();
      }
    };
    return {
       payWay: "3",
      dialogVisible: false,
      loading: false,
      huishouObj: "",
      checkList: [],
      baopeiList: [],
      baopeiBankList: [],
      sellerBankList: [],
      ruleForm: {
        backClueId: "",
        backAmount: "",
        guaranteeAmount: "",
        guaranteeTenantId: "",
        guaranteeTenantCollection: "",
        guaranteeInfo: "",
        remark: "",
        actualAmount: "",
        accountPassword: "",
        securityPhone: "",
        zhanghu: "",
        accountNumber: "",
        sellerId: "",
        zhanghuSeller: "",
        guaranteeId:'',
        guaranteeName:'',
        guaranteeServiceAmount:'',
        buyerActualAmount:''
      },
      sellerKefuList: [],
      isJingpai: false,
      rules: {
        // saleChanelId:[
        // { required: true, message: '请选择买家', trigger: 'blur' }
        // ],
        backAmount: [
          { required: true, message: "请输入回收金额", trigger: "blur" },
          { validator: priceRule, trigger: "blur" },
        ],
        guaranteeAmount: [
          { required: true, message: "请输入包赔费", trigger: "blur" },
          { validator: priceRule, trigger: "blur" },
        ],
        
         guaranteeId: [
          { required: true, message: "请输入选择包赔客服", trigger: "change" },
        ],
        zhanghu: [
          { required: true, message: "请输入选择收款账户", trigger: "change" },
        ],
        sellerId: [
          { required: true, message: "请选择卖家客服", trigger: "change" },
        ],
        zhanghuSeller: [
          { required: true, message: "请选择卖家收款账户", trigger: "change" },
        ],
        securityPhone: [{ validator: phoneRule, trigger: "blur" }],
      },
      kefuList: [],
      baopeiDuanSetObj:null,
      xiansuofei:0
    };
  },
  computed: {
     shopInfo() {
      return this.$store.getters.shopInfo;
    },
  },
  created() {
    
    console.log(this.shopInfo,'99')
  },
  methods: {
        //选择支付方式
    selectPayway(e) {
      this.payWay = e;
    },
    open(info, shimingData, isJingpai) {
      console.log("%c Line:209 🥓 info", "color:#b03734", info , shimingData , isJingpai);
      this.loading = false;
      this.huishouObj = info;
      this.dialogVisible = true;
      this.getBaopeiList();
      this.kefuList = [];
      this.$nextTick(() => {
        this.resetForm();
        if (shimingData) {
          shimingData.ip = this.huishouObj.ip;
          shimingData.ipAddr = this.huishouObj.ipAddr;
          this.ruleForm.guaranteeInfo = JSON.stringify(shimingData);
        }
        if (isJingpai) {
          this.ruleForm.backAmount = this.huishouObj.backAmount;
          this.ruleForm.actualAmount = this.huishouObj.backAmount;
          this.isJingpai = true;
          this.getSellerBankList(this.huishouObj.sourceTenantId);
          this.getsellerKefuList();
          this.ruleForm.guaranteeInfo = JSON.stringify({});
        }
        this.ruleForm.actualAmount = 0
        if(info.source==4) { // 说明是竞价回收, 回收金额不可更改, 包赔是必填
          this.ruleForm.backAmount = this.huishouObj.backAmount;
         
          if(this.shopInfo.backFixedPrice || this.shopInfo.backRatioPrice) {
            this.calculateFees()
          }else {
              this.getLeadFee()
          }
        }
        this.ruleForm.backClueId = this.huishouObj.id;
        this.ruleForm.accountNumber = this.huishouObj.accountNumber;
      });
    },
    // 计算线索费和实际金额
calculateFees() {
  // 重置线索费
  this.xiansuofei = 0;
  
  // 存在固定值或比例值时才计算
  if (this.shopInfo.backFixedPrice !== undefined || this.shopInfo.backRatioPrice !== undefined) {
    // 固定值处理（转换为数字，默认0）
    const fixedPrice = Number(this.shopInfo.backFixedPrice) || 0;
    
    // 比例值处理（转换为数字，默认0）
    const ratioPrice = this.shopInfo.backRatioPrice 
      ? Math.round(Number(this.huishouObj.backAmount) * Number(this.shopInfo.backRatioPrice) / 100)
      : 0;
      
    // 计算总和（固定值 + 比例值）
    this.xiansuofei = fixedPrice + ratioPrice;
  }
  
  // 计算实际金额（回收金额 + 线索费）
  this.ruleForm.actualAmount = (Number(this.huishouObj.backAmount) || 0) + this.xiansuofei;
},
    getLeadFee() {
       this.getDicts("leadFee").then(res=>{
        if(res.data&&res.data.length){
         const xiaoshuo1= Number(res.data[0].dictValue) ;
         const xiaoshuo2= Math.round(Number(this.huishouObj.backAmount) * Number(res.data[1].dictValue) / 100);
           this.xiansuofei = xiaoshuo1 + xiaoshuo2;
          this.ruleForm.actualAmount = Number(this.huishouObj.backAmount) + Number(this.xiansuofei);
        }
      })
    },
    // 查询卖家所有竞拍客服
    getsellerKefuList() {
      let paramsObj = {
        tenantId: this.huishouObj.sourceTenantId,
        typeArr: [4],
        workState: 1,
      };
      kefuApi.getList(paramsObj).then((res) => {
        if (res.rows && res.rows.length) {
          this.sellerKefuList = res.rows;
        }
      });
    },
    // 获取包赔商的客服列表
    getKefuList(tenantId) {
      kefuApi
        .getList({
          tenantId: tenantId,
          typeArr: [3],
          workState: 1,
        })
        .then((res) => {
          if (res.rows) {
            this.kefuList = res.rows;
          }
        });
    },
    // 选择包赔客服
    kefuChange(e) {
      if (e && this.kefuList.length) {
        this.kefuList.forEach((r) => {
          if (r.customer == e) {
            this.ruleForm.guaranteeName = r.name;
          }
        });
      }
    },

    // 查询所有开通包赔商服务的店铺
    getBaopeiList() {
      this.loading = true;
      phoneApi
        .getIsLeaseTenantList({
          groupKey: "baopeishang",
        })
        .then((response) => {
          console.log("%c Line:198 🍔 response", "color:#b03734", response);
          this.baopeiList = response.data;
          this.loading = false;
        });
    },
    // 如果是竞拍  查询卖家的账户列表
    getSellerBankList(tenantId) {
      // console.log("%c Line:181 🍔 tenantId", "color:#b03734", tenantId);
      this.loading = true;
      onSelfApi
        .getBankListByTenantId({
          tenantId: tenantId,
          partyType:1
        })
        .then((response) => {
          this.sellerBankList = response.data;
          this.loading = false;
        });
    },
    // 选择卖家账户
    zhanghuChangeSeller(e) {
      if (e && this.sellerBankList.length) {
        this.sellerBankList.forEach((r) => {
          if (r.id == e) {
            this.ruleForm.guaranteeInfo = JSON.stringify({
              collectionRemark: `${r.collectionAccount} ${r.collectionAccountName} ${r.collectionUserName}`,
            });
          }
        });
      }
    },
    // 选择包赔商
    tenantChange(item) {
      
      if (this.ruleForm.guaranteeTenantId != item.tenantId) {
        this.getBaopeiDuanSetting(item)
      }else{
        this.ruleForm.guaranteeTenantId = "";

        this.ruleForm.guaranteeAmount = "";
        this.ruleForm.guaranteeServiceAmount = "";
        this.baopeiBankList = [];
        this.ruleForm.guaranteeName = ''
        this.ruleForm.guaranteeId = ''
        this.ruleForm.guaranteeTenantCollection = ''
        this.ruleForm.zhanghu = ''
        this.baopeiDuanSetObj = null
        this.kefuList = []
        this.computedTotal();
      }
      
    },
    // 查询包赔商的 包赔端设置
    getBaopeiDuanSetting(item){
      // 获取供货商的包赔配置 customerServiceApi
      if(item.tenantId){
        customerServiceApi
        .getConfigByTenantId({
          configKey: "guaranteeServiceAmount",
          tenantId: item.tenantId,
        })
        .then((res) => {
          if (
            res.data &&
            res.data.configValue
          ) {
            this.ruleForm.guaranteeAmount = "";
            this.ruleForm.guaranteeServiceAmount = "";
            this.baopeiBankList = [];
            this.ruleForm.guaranteeName = ''
            this.ruleForm.guaranteeId = ''
            this.ruleForm.guaranteeTenantCollection = ''
            this.ruleForm.zhanghu = ''
            this.baopeiDuanSetObj = null
            this.kefuList = []

            this.ruleForm.guaranteeTenantId = item.tenantId;
            this.getBaopeiBankList(this.ruleForm.guaranteeTenantId);
            this.getKefuList(this.ruleForm.guaranteeTenantId)
            this.baopeiDuanSetObj = JSON.parse(res.data.configValue);
            this.computedTotal();
          }else{
            this.$message.error('该包赔商未设置包赔费规则，无法选择！')
          }
        });
      }
      
    },
    // 计算包赔费
    computedTotal(){
      if(this.baopeiDuanSetObj){
          const shouxufei = this.baopeiDuanSetObj.shouxufie||0
          const baifenbi = this.baopeiDuanSetObj.baifenbi?(this.baopeiDuanSetObj.baifenbi/100):0
          const minNum = this.baopeiDuanSetObj.minNum?Number(this.baopeiDuanSetObj.minNum):0
          const backAmount = this.ruleForm.backAmount||0
          this.ruleForm.guaranteeServiceAmount = Number(shouxufei)
          const baopeifei = Number(backAmount)*baifenbi
          console.log("%c Line:358 🍅 baopeifei", "color:#42b983", baopeifei);
          this.ruleForm.guaranteeAmount = Math.floor(minNum>baopeifei?minNum:baopeifei);
          this.priceChange()
      }else{
          this.ruleForm.guaranteeAmount = ''
          this.ruleForm.guaranteeServiceAmount = ''
          this.priceChange()
      }
    },
    // 查询包赔商的收款账户列表
    getBaopeiBankList(tenantId) {
      // console.log("%c Line:181 🍔 tenantId", "color:#b03734", tenantId);
      this.loading = true;
      onSelfApi
        .getBankListByTenantId({
          tenantId: tenantId,
          partyType:1
        })
        .then((response) => {
          this.baopeiBankList = response.data;
          this.loading = false;
        });
    },
    // 选择包赔账户
    zhanghuChange(e) {
      if (e && this.baopeiBankList.length) {
        this.baopeiBankList.forEach((r) => {
          if (r.id == e) {
            this.ruleForm.guaranteeTenantCollection = JSON.stringify(r);
          }
        });
      }
    },
    // 黑号查询
    heihaoCheck() {
      const account = this.huishouObj.accountNumber;
      if (account) {
        this.loading = true;
        listBlack({
          content: account,
        })
          .then((res) => {
            this.loading = false;
            console.log("%c Line:235 🍊 res", "color:#4fff4B", res);
            if (res.rows && res.rows.length) {
              this.$alert("当前账号是黑号！请谨慎交易！");
            } else {
              this.$alert("当前账号不是黑号！");
            }
          })
          .catch((err) => {
            this.loading = false;
          });
      }
    },

    // 计算实付金额
    priceChange() {
      if (this.ruleForm.guaranteeTenantId) {
        if (this.ruleForm.backAmount && this.ruleForm.guaranteeAmount) {
          const shouxufei = this.ruleForm.guaranteeServiceAmount?Number(this.ruleForm.guaranteeServiceAmount):0
          let num =
            Number(this.ruleForm.backAmount) +
            Number(this.ruleForm.guaranteeAmount)+shouxufei
          num = Math.round(num * 100) / 100;
       
          this.ruleForm.actualAmount = num + Number(this.xiansuofei);
        }
      } else {
        if (this.ruleForm.backAmount) {
          let num = Number(this.ruleForm.backAmount);
          num = Math.round(num * 100) / 100;
          this.ruleForm.actualAmount = num + Number(this.xiansuofei);
        }
      }
    },

    submitForm(formName) {
      if(this.huishouObj.source == 4 && !this.ruleForm.guaranteeTenantId){
       this.$message.error('竞价回收必须选择包赔商！')
         return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("确定回收该商品吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.loading = true;
                   if (this.huishouObj.source == 4) { // 需要支付
            if (this.shopInfo.availableMoney < this.ruleForm.actualAmount) {
              this.$confirm(`余额不足,无法支付，请充值`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$refs.chongzhiYue.open();
              });
              this.loading = false;
              return; // 🆕 余额不足直接 return，不再调用接口
            }
          }
          this.ruleForm.buyerActualAmount = this.ruleForm.actualAmount
              onSelfApi
                .backClueOrderAdd(this.ruleForm)
                .then((res) => {
                  this.loading = false;
                  if (res.code == 200) {
                    // 下单成功
                    this.$message.success("订单提交成功");
                   
                    this.$parent.getList();
                    this.close();
                    this.$router.push({
                      path: "/recycleManage/recycleOrdersmyBuy",
                    });
                  }
                })
                .catch((err) => {
                  this.loading = false;
                });
            })
            .catch(() => {});
        } else {
          //console.log("error submit!!");
          return false;
        }
      });
    },

    resetForm() {
      this.$refs["ruleForm"].resetFields();
    },
    close(formName) {
      this.resetForm();
      this.$emit("close");
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.sfk {
  text-align: right;
  padding-right: 20px;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 10px;

  .txt {
    font-size: 26px;
    color: #ff0000;
    margin-left: 5px;
  }
}

.pick-dialog >>> .el-input--medium input {
  text-align: left;
}
.tip {
  text-align: center;
  color: #999;
  margin-bottom: 10px;
}
.baopei-box {
  width: 100%;
  padding-bottom: 6px;
  padding-left: 20px;
  >div{
    flex-wrap: wrap;
    gap:10px;
  }
  .baopei-item {
    border-radius: 12px;
    max-width: 300px;
    border: 1px solid #eae8e8;
    padding: 10px 10px;
    cursor: pointer;
    user-select: none;
    > img {
      border-radius: 10px;
      margin-right: 15px;
    }
    .tit {
      font-size: 16px;
      // font-weight: 600;
      // line-height: 16px;
      // margin-bottom: 5px;
      max-width: 190px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      margin-right: 10px;
    }
    .des {
      width: 180px;
      height: 36px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      line-height: 18px;
      font-size: 12px;
    }
    .icon {
      height: 22px;
      // margin-top: 3px;
      text-align: right;
      img {
        width: 22px;
        height: 22px;
        cursor: pointer;
      }
    }
    &.active {
      background: #6c5dd3;
      color: #fff;
    }
  }
}
</style>
